#include "stdafx.h"
#include <JeayeSDK\JLink.h>

JLink::JLink()
{
	clean_up();
}

stLinkIterator * JLink::pop_front()
{
	stLinkIterator *ret = NULL;
	if (is_empty() == TRUE)
		return NULL;

	ret = this->head;
	this->head = ret->next;

	if (this->head != NULL) {
		this->count--;
		_ASSERT(this->count >= 0);
	}
	else if (this->tail == ret) {
		/* link is empty clear link */
		this->head = this->tail = NULL;
		this->count = 0;
	}
	else {
		_ASSERT(FALSE);
	}

	ret->next = NULL;

	return ret;
}

BOOL JLink::push_front(stLinkIterator * pItem)
{
	pItem->next = NULL;

	if (this->head == NULL) {
		this->tail = pItem;
	}
	else {
		pItem->next = this->head;
	}

	this->head = pItem;
	this->count++;

	return TRUE;
}

BOOL JLink::push_back(stLinkIterator * pItem)
{
	pItem->next = NULL;

	if (this->head == NULL) {
		this->head = pItem;
	}
	else {
		this->tail->next = pItem;
	}
	this->tail = pItem;
	this->count++;

	return TRUE;
}

BOOL JLink::append(JLink * append)
{
	if (append == NULL || append->is_empty() == TRUE)
		return FALSE;

	if (is_empty() == TRUE) {
		this->head = append->head;
		this->tail = append->tail;
		this->count = append->count;

		return TRUE;
	}

	if (this->head == NULL) {
		this->head = append->head;
	}
	else {
		this->tail->next = append->head;
	}

	this->tail = append->tail;
	this->count += append->count;

	return TRUE;
}

stLinkIterator * JLink::first()
{
	return this->head;
}

stLinkIterator * JLink::last()
{
	return this->tail;
}

void JLink::clean_up()
{
	this->head = this->tail = NULL;
	this->count = 0;
}
